import {
  AuditEntMgtParam,
  AuthEntMgtParam,
  DecrytionParam,
  EtpMgtTableItem,
  EtpMgtTableParams,
  StatusItem,
  UpdateEntMgtParam,
} from './model/enterpriseManagementModel';
import { formatToDateTime } from '/@/utils/dateUtil';
import { loginHttp, tenantHttp } from '/@/utils/http/axios';

import dayjs from 'dayjs';

enum Api {
  GET_ENTERPRISE_MGT_TABLE = '/tenant/page',
  GET_STATUS_OPTIONS = '/tenant/status',
  EDIT = '/tenant/update',
  AUDIT = '/tenant/audit',
  AUTH = '/appAuthorization/createTenantAppAuthByTenant',
  DETAIL = '/tenant/getTenantDetail',
  DECRYPTION = '/tenant/getDecryptionData',
  REGISTEER = '/origin/addTenantAccount',
}

export const getEnterpriseMgtTable = async (params: EtpMgtTableParams) => {
  const res = await tenantHttp.post<EtpMgtTableItem>({
    url: Api.GET_ENTERPRISE_MGT_TABLE,
    params,
  });

  res.items.map((item) => {
    item.enabledStr = item.enabled ? '是' : '否';
    item.isBuiltInStr = item.isBuiltIn ? '是' : '否';
    if (formatToDateTime(item.registerTime) !== 'Invalid date') {
      item.registerTime = formatToDateTime(item.registerTime);
    }
    if (item.channel === null || item.channel === 'null') {
      item.channel = '--';
    }
    if (item.expireTime !== '--' && item.expireTime !== 'Invalid Date' && item.expireTime !== null) {
      item.expireTimeDjs = dayjs(item.expireTime).format('YYYY-MM-DD HH:mm:ss');
    }

    return item;
  });
  return res;
};

export const getStatusOpt = async () => {
  const res = await tenantHttp.get<StatusItem[]>({
    url: Api.GET_STATUS_OPTIONS,
  });

  const result = res.map((item) => {
    return {
      label: item.desc,
      value: item.status,
    };
  });

  return result;
};

export const auditEntMgt = async (params: AuditEntMgtParam) => {
  const res = await tenantHttp.post<string>({
    url: Api.AUDIT,
    params,
  });
  return res;
};

export const authEntMgt = async (params: AuthEntMgtParam) => {
  const res = await tenantHttp.post<string>({
    url: Api.AUTH,
    params,
  });
  return res;
};
export const getEntDetail = async (param: number) => {
  const params = { tenantId: param };
  const res = await tenantHttp.get<UpdateEntMgtParam>({
    url: Api.DETAIL,
    params,
  });
  return res;
};
export const getDecrytion = async (params: DecrytionParam) => {
  const res = await tenantHttp.post<string>({
    url: Api.DECRYPTION,
    params,
  });
  return res;
};

export const updateEntMgt = async (files: File[], data: UpdateEntMgtParam) => {
  data.deleteImagesList = JSON.stringify(data.deleteImagesList);
  const res = await tenantHttp.uploadFile({ url: '/api/admin/saaslandingTenant' + Api.EDIT }, { files, data });
  return res;
};

export async function proxyRegister(files: File[], data: UpdateEntMgtParam) {
  data.type = 1;
  const res = await loginHttp.uploadFile({ url: '/api/admin/saaslanding-auth' + Api.REGISTEER }, { files, data });
  return res;
}
